//
//  GenericTableViewController.m
//  ClinicalCollections
//
//  Created by janakiraman gopinath on 12/29/12.
//  Copyright (c) 2012 GOPI. All rights reserved.
//

#import "GenericTableViewController.h"

@interface GenericTableViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIActivityIndicatorView *spinner;

@end

@implementation GenericTableViewController :UITableViewController


@synthesize search = _search;
@synthesize annotations = _annotations;
@synthesize lastIndexPath = _lastIndexPath;
@synthesize searchIndex = _searchIndex;
@synthesize filterSet = _filterSet;
@synthesize filteredListContent = _filteredListContent;
@synthesize refresh = _refresh;
@synthesize spinner = _spinner;

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.lastIndexPath == nil) {
        self.lastIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        if (self.filterSet && [[self.filteredListContent allKeys] count] == 1) {
            [self.tableView selectRowAtIndexPath:self.lastIndexPath
                                        animated:YES
                                  scrollPosition:UITableViewScrollPositionNone];
            [self tableView:self.tableView didSelectRowAtIndexPath:self.lastIndexPath];
            
        }
    }
    else
        [self.tableView selectRowAtIndexPath:self.lastIndexPath
                                    animated:YES
                              scrollPosition:UITableViewScrollPositionNone];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    [self loadAnnotations:nil];
    
    
    ClinicalCollectionsViewController *ccvc = [[CommonAPI class] targetViewControllerFrom:self
                                                                                  forPath:NA
                                                                                     side:RIGHT
                                                                  returningViewController:CLINICALCOLLECTIONSVIEWCONTROLLER ];
    ccvc.search = self.search;
    //
    // Enable the search bar on Right hand side splitView (detailed view)
    // Enabling search button on the generic table view controller is not looking nice
    
    [ccvc hideSearchBar:NO];
    
    //
    // If the keyboard is active resign it from the previous search dismiss it
    // Clear any data present in the view
    [[CommonAPI class] clearKeyboardAndSearchText:ccvc];
    
    [[CommonAPI class] setupNotification:RECENT_EVENTS
                                     for:self
                                selector:@selector(recentNotification:)];
    
}
- (void) recentNotification:(NSNotification *) notification
{
    NSString *nctID = [[notification.object componentsSeparatedByString:@","] objectAtIndex:0];
    NSString *title = [[notification.object componentsSeparatedByString:@","] objectAtIndex:1];
    
    ClinicalTrialGov *clinGov = [[CommonAPI class] clinicalTrialGov:nctID fromSearch:self.search];
    
    
    if (clinGov == nil || !clinGov)
        self.search = [[ClinicalTrialGov class] SearchForClinicalTrialGov:nctID
                                                                  context:[[DatabaseHelper class] database].managedObjectContext];
    
    NSDictionary *cache = [[NSDictionary alloc] initWithDictionary:self.filteredListContent];
    NSDictionary *tempDictionary;
    
    [self.filteredListContent removeAllObjects];
    self.filterSet = NO;
    self.title = title;
    tempDictionary = [[CommonAPI class] searchData:self.search
                                        searchText:nctID];
    if ([[tempDictionary allKeys] count]) {
        self.filterSet = YES;
        [self.filteredListContent addEntriesFromDictionary:tempDictionary];
        
        
    }
    if (self.filterSet && ![self.filteredListContent isEqual:cache]) {
        [self.tableView reloadData];
        
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
                                    animated:YES scrollPosition:UITableViewScrollPositionNone];
        [self tableView:self.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    }
    else if(!self.filterSet) {
        [self.filteredListContent removeAllObjects];
        self.filterSet = NO;
        [self.tableView reloadData];
        
    }
}


- (UIActivityIndicatorView *)spinner {
    if (!_spinner) {
        _spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return _spinner;
}

- (IBAction) refresh:(UIBarButtonItem *)sender;
{
    self.filterSet = NO;
    [self.filteredListContent removeAllObjects];
    ClinicalCollectionsViewController *ccvc = [[CommonAPI class] targetViewControllerFrom:self
                                                                                  forPath:NA
                                                                                     side:RIGHT
                                                                  returningViewController:CLINICALCOLLECTIONSVIEWCONTROLLER ];
    ccvc.search = self.search;
    //
    // Enable the search bar on Right hand side splitView (detailed view)
    // Enabling search button on the generic table view controller is not looking nice
    
    [ccvc hideSearchBar:NO];
    
    //
    // If the keyboard is active resign it from the previous search dismiss it
    // Clear any data present in the view
    [[CommonAPI class] clearKeyboardAndSearchText:ccvc];
    [self refreshMap:ccvc forIndexPath:nil];
    [self.tableView reloadData];
}
- (void) loadAnnotations:(ClinicalTrialGov *) clinicalTrialGov
{
    
    id vc = [self.splitViewController.viewControllers lastObject];
    id mvc = [[vc viewControllers] objectAtIndex:0];
    
    Class cls = [CommonAPI class];
    if (clinicalTrialGov) {
        NSMutableArray *locationsArray = [[NSMutableArray alloc] initWithCapacity:MAX_CAPACITY];
        
        [cls mergeArray:locationsArray
              withArray:[cls createAnnotations:[clinicalTrialGov.location allObjects]
                             primaryAnnotation:NO
                              accessoryEnabled:NO
                                         title:clinicalTrialGov.nctID]];
        
        [cls mergeArray:locationsArray
              withArray:[cls createAnnotations:[[NSArray alloc] initWithObjects:clinicalTrialGov, nil]
                             primaryAnnotation:YES
                              accessoryEnabled:YES
                                         title:@""]];
        self.annotations = locationsArray;
        
    }
    else {
        // ClinicalAnnotation
        NSArray     *clinicalTrialGovArray = [self.search.clinicalTrialGov allObjects];
        self.annotations = [cls createAnnotations:clinicalTrialGovArray
                                primaryAnnotation:YES
                                 accessoryEnabled:YES
                                            title:@""];
        
    }
    ((ClinicalCollectionsViewController *)mvc).annotations = self.annotations;
    
}

- (NSMutableDictionary *) filteredListContent {
    if (!_filteredListContent)
        _filteredListContent = [[NSMutableDictionary alloc] initWithCapacity:MAX_CAPACITY];
    return _filteredListContent;
}

#pragma mark - Table view data source


- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.filterSet) {
        return [self.filteredListContent.allKeys count];
    }
    else
        return [[self.search.status allObjects] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.filterSet) {
        NSString *key = [[self.filteredListContent allKeys] objectAtIndex:section];
        
        return [[self.filteredListContent valueForKey:key] count];
    }
    else {
        Status *status = [[self.search.status allObjects] objectAtIndex:section];
        return [[status.clinicalTrialGov allObjects] count];
    }
}

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.filterSet) {
        NSString *key = [[self.filteredListContent allKeys] objectAtIndex:section];
        NSUInteger count = [[self.filteredListContent valueForKey:key] count];
        return [NSString stringWithFormat:@"%@ [%d]", key, count];
    }
    else {
        Status *status = [[self.search.status allObjects] objectAtIndex:section];
        return [NSString stringWithFormat:@"%@:(%d)",status.status,
                [[status.clinicalTrialGov allObjects] count]];
    }
}


- (void) tableView:(UITableView *)tableView
   willDisplayCell:(UITableViewCell *)cell
 forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ClinicalTrialGov *clinicalTrialGov;
    if (self.filterSet) {
        NSString *key = [[self.filteredListContent allKeys] objectAtIndex:indexPath.section];
        NSString *nctId = [[self.filteredListContent valueForKey:key] objectAtIndex:indexPath.row];
        clinicalTrialGov = [[CommonAPI class] clinicalTrialGov:nctId
                                                    fromSearch:self.search];
    }
    else {
        Status *status = [[self.search.status allObjects] objectAtIndex:indexPath.section];
        clinicalTrialGov = [[status.clinicalTrialGov allObjects] objectAtIndex:indexPath.row];
    }
    if ([[[[clinicalTrialGov.groupTypes allObjects] objectAtIndex:0] measure] count] > 0 && ![clinicalTrialGov.groupTypes isEqual:[NSNull null]]) {
        UIImageView *star = [[UIImageView alloc]initWithFrame:CGRectMake(275,2, 20, 25)];
        star.image=[UIImage imageNamed:@"28-star.png"];
        [cell addSubview:star];
        
    }
    
}

- (void) removeResultsWhichGetsCarriedOverFromDeqeueResuable
{
    NSArray *cells = [self.tableView visibleCells];
    
    for (int i = 0; i < cells.count; i++) {
        UITableViewCell *cell = cells[i];
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        // Add * to indicate that the study has results
        
        Status *status = [[self.search.status allObjects] objectAtIndex:indexPath.section];
        
        ClinicalTrialGov *clinicalTrialGov = [[status.clinicalTrialGov allObjects] objectAtIndex:indexPath.row];
        
        // Check the noOfParticipants sometimes groups does have data and no_of_participants
        // This will end up creating a blank graph
        if ([[[[clinicalTrialGov.groupTypes allObjects] objectAtIndex:0] measure] count] > 0 && ![clinicalTrialGov.groupTypes isEqual:[NSNull null]]) {
            UIImageView *star = [[UIImageView alloc]initWithFrame:CGRectMake(275,2, 20, 25)];
            star.image=[UIImage imageNamed:@"28-star.png"];
            [cell addSubview:star];
        }
        else
            // Remove the star  image if present which might get carried over from the dequeResuable
            for (id views in cell.subviews)
                if ([views isKindOfClass:[UIImageView class]])
                    [views removeFromSuperview];
        
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Study cells";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    [[CommonAPI class] removeImageViewFromCell:cell];
    
    NSString *titleString, *subTitleString;
    
    
    ClinicalTrialGov *clinicalTrialGov;
    
    if (self.filterSet) {
        
        NSString *key = [[self.filteredListContent allKeys] objectAtIndex:indexPath.section];
        NSString *nctId = [[self.filteredListContent valueForKey:key] objectAtIndex:indexPath.row];
        clinicalTrialGov = [[CommonAPI class] clinicalTrialGov:nctId
                                                    fromSearch:self.search];
    }
    
    else
    {
        Status *status = [[self.search.status allObjects] objectAtIndex:indexPath.section];
        clinicalTrialGov = [[status.clinicalTrialGov allObjects] objectAtIndex:indexPath.row];
    }
    NSArray *conditionArray = [clinicalTrialGov.condition allObjects];
    
    
    for(int i = 0; i < conditionArray.count; i++)
        if(!i) titleString = [NSString stringWithFormat:@"%@" , ((Condition *)conditionArray[i]).condition];
        else
            titleString = [NSString stringWithFormat:@"%@,%@", titleString, ((Condition *)conditionArray[i]).condition];
    
    subTitleString= [NSString stringWithFormat:@"%@,%@" , clinicalTrialGov.nctID, clinicalTrialGov.briefTitle];
    
    
    
    cell.textLabel.text = titleString;
    cell.detailTextLabel.text = subTitleString;
    
    return cell;
}
#pragma mark - Table view delegate

- (void) refreshMap:(id) clinicalCollectionsViewController
       forIndexPath:(NSIndexPath *)indexPath
{
    ClinicalAnnotation *cl;
    ClinicalTrialGov *clinicalTrialGov;
    
    if (indexPath != nil)
    {
        if (self.filterSet) {
            
            NSString *key = [[self.filteredListContent allKeys] objectAtIndex:indexPath.section];
            NSString *nctId = [[self.filteredListContent valueForKey:key] objectAtIndex:indexPath.row];
            
            clinicalTrialGov = [[CommonAPI class] clinicalTrialGov:nctId
                                                        fromSearch:self.search];
        }
        else
        {
            Status *status = [[self.search.status allObjects] objectAtIndex:indexPath.section];
            clinicalTrialGov = [[status.clinicalTrialGov allObjects] objectAtIndex:indexPath.row];
        }
        [self loadAnnotations:clinicalTrialGov];
    }
    else
        [self loadAnnotations:nil];
    
    for (int i = 0; i < self.annotations.count; i++)
        if([[self.annotations[i] subTitile] isEqualToString:clinicalTrialGov.city] &&
           [[self.annotations[i] title] isEqualToString:clinicalTrialGov.nctID])
            cl = self.annotations[i];
    
    cl.primary = YES;
    cl.noAccessory = NO;
    
    [[clinicalCollectionsViewController mapView] selectAnnotation:cl animated:YES];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.lastIndexPath = indexPath;
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    Class cls = [CommonAPI class];
    
    ClinicalCollectionsViewController *ccvc = [cls targetViewControllerFrom:self
                                                                    forPath:NA
                                                                       side:RIGHT
                                                    returningViewController:CLINICALCOLLECTIONSVIEWCONTROLLER];
    // Get rid of the keyboard if it is present
    // Clear any text if present from the last search
    [[CommonAPI class] clearKeyboardAndSearchText:ccvc];
    
    //first we try to update the map view
    //this should happen even if we have segue'd deeper down the stack
    if(ccvc && ![ccvc isEqual:[NSNull null]] &&
       [ccvc isKindOfClass:[ClinicalCollectionsViewController class]] &&
       ccvc.mapView.window) {
        
        [self refreshMap:ccvc forIndexPath:indexPath];
    }
    
    //Next we will try to update if we have a view study
    id mvc = [cls targetViewControllerFrom:self
                                   forPath:NA
                                      side:RIGHT
                   returningViewController:CCVIEWSTUDYVIEWCONTROLLER];
    if ([mvc isKindOfClass:[CCViewStudyViewController class]]) {
        NSString *nctId = [[cell.detailTextLabel.text
                            componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@COMMA]] objectAtIndex:0];
        [(CCViewStudyViewController*)mvc loadViewDataByNtcID:nctId fromSearch:self.search];
    }
    
    //Next we will try to update if we have a webview
    mvc = [cls targetViewControllerFrom:self
                                forPath:NA
                                   side:RIGHT
                returningViewController:CLINICALTRIALWEBVIEWCONTROLLER];
    
    if ([mvc isKindOfClass:[ClinTrialWebViewController class]] && ((ClinTrialWebViewController *) mvc).webView.window) {
        NSString *nctId = [[cell.detailTextLabel.text
                            componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@COMMA]] objectAtIndex:0];
        NSString *url = [NSString stringWithFormat:@CLINICAL_COLLECTIONS_URL,
                         nctId];
        ((ClinTrialWebViewController *)mvc).url = url;
        
    }
    //Next we will try to update if we have a graph
    mvc = [cls targetViewControllerFrom:self
                                forPath:NA
                                   side:RIGHT
                returningViewController:GRAPHVIEWCONTROLLER];
    
    if ([mvc isKindOfClass:[GraphViewController class]] && ((GraphViewController *) mvc).collectionView.window) {
        NSString *nctId = [[cell.detailTextLabel.text
                            componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@COMMA]] objectAtIndex:0];
        
        ClinicalTrialGov *clinicalTrialGov = [[CommonAPI class]
                                              clinicalTrialGov:[NSString stringWithFormat:@"%@",nctId]                    fromSearch:self.search];
        ((GraphViewController *)mvc).clinicalTrialGov = clinicalTrialGov;
        [((GraphViewController *) mvc) reload];
        
    }
    
}


@end
